package net.khoroshev.wschat.web.auth;

import net.khoroshev.wschat.service.auth.AuthService;
import net.khoroshev.wschat.web.View;
import net.khoroshev.wschat.web.validator.UserValidator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.Errors;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created with IntelliJ IDEA.
 * Created by: vfirstov
 * Date: 16.11.13
 * Time: 21:03
 *
 */

@Controller
@SessionAttributes(View.MODEL_OBJECT_USER)
public class AuthController implements View {

    private static final Log logger = LogFactory.getLog(AuthController.class);

    @Autowired
    AuthService authService;

    @Autowired
    UserValidator userValidator;


    /*  sign ip processing */

    @RequestMapping(value = "signup")
    public String showSignUp(ModelMap model) {
        model.addAttribute(View.MODEL_OBJECT_USER, new FormAuthUser());
        return SIGN_UP_VIEW;
    }


    @RequestMapping(value = "signup", method = RequestMethod.POST)
    public ModelAndView signUp(@ModelAttribute(MODEL_OBJECT_USER) FormAuthUser user, Errors errors, RedirectAttributes ra) {

        userValidator.validateSignUp(user, errors);

        if (errors.hasErrors()) {
            ModelAndView mav = new ModelAndView(SIGN_UP_VIEW);
            mav.addObject(MODEL_OBJECT_USER, user);
            return mav;
        }

        authService.addUser(user.getFirstName(), user.getLastName(), user.getUserName(), user.getPassword());

        return new ModelAndView(SIGN_IN_VIEW);
    }



    /*  sign in processing */

    @RequestMapping(value = "login")
    public String showSignIn(ModelMap model) {
        model.addAttribute(View.MODEL_OBJECT_USER, new FormAuthUser());
        return SIGN_IN_VIEW;
    }



    @RequestMapping(value = "login", method = RequestMethod.POST)
    public ModelAndView signIn(@ModelAttribute(MODEL_OBJECT_USER) FormAuthUser user, Errors errors, RedirectAttributes ra) {

        userValidator.validateSignIn(user, errors);

        if (errors.hasErrors()) {
            ModelAndView mav = new ModelAndView(SIGN_IN_VIEW);
            mav.addObject(MODEL_OBJECT_USER, user);
            return mav;
        }

        return new ModelAndView(SUCCESS_VIEW);
    }
}
